package com.example.peibei.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.GlideUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.IdentityCheckedPresenter;
import com.example.peibei.service.presenter.IdentityCheckedPresenterTwo;
import com.example.peibei.service.presenter.SaveFaceImagePresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.ui.weight.AddressPickTask;
import com.example.peibei.ui.weight.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;

public class IdentityCheckedActivity extends WDActivity {
    @BindView(R.id.et_realname)
    EditText et_realname;
    @BindView(R.id.rl_sex)
    RelativeLayout rl_sex;
    @BindView(R.id.rl_birthday)
    RelativeLayout rl_birthday;
    @BindView(R.id.et_sex)
    TextView et_sex;
    @BindView(R.id.et_birthday)
    TextView et_birthday;
    @BindView(R.id.et_address)
    TextView et_address;
    @BindView(R.id.et_number)
    EditText et_number;
    @BindView(R.id.bt_save)
    Button bt_save;

    @BindView(R.id.iv_face_one)
    ImageView iv_face_one;
    @BindView(R.id.iv_face_two)
    ImageView iv_face_two;
    @BindView(R.id.ll_add_img_one)
    LinearLayout ll_add_img_one;
    @BindView(R.id.ll_progress)
    LinearLayout ll_progress;
    @BindView(R.id.ll_progress_two)
    LinearLayout ll_progress_two;
    @BindView(R.id.ll_add_img_two)
    LinearLayout ll_add_img_two;

    @BindView(R.id.iv_img_one)
    ImageView iv_img_one;
    @BindView(R.id.rl_add_one)
    RelativeLayout rl_add_one;
    @BindView(R.id.iv_img_two)
    ImageView iv_img_two;
    @BindView(R.id.rl_add_two)
    RelativeLayout rl_add_two;
    @BindView(R.id.iv_img_three)
    ImageView iv_img_three;
    @BindView(R.id.rl_add_three)
    RelativeLayout rl_add_three;

    private SPUtils spUtils;
    private String token;
    private String sex;
    private String address;
    private String birthday;
    private long mid;
    private IdentityCheckedPresenter identityCheckedPresenter;

    private UploadImagePresenter uploadImagePresenter;
    private UploadImagePresenter uploadImagePresenterTwo;
    private SaveFaceImagePresenter saveFaceImagePresenter;
    private IdentityCheckedPresenterTwo identityCheckedPresenterTwo;
    private int type;
    private String imgPathone;
    private String imgPathtwo;
    private String number;
    private String realName;
    String imagePathOne = "";
    String imagePathTwo = "";
    String imagePathThree = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_identiy_checked;
    }

    @Override
    protected void initView() {
        spUtils = new SPUtils(IdentityCheckedActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        mid = spUtils.getLong("mid");
        identityCheckedPresenterTwo = new IdentityCheckedPresenterTwo(new EditUserInfoCall());
        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        uploadImagePresenterTwo = new UploadImagePresenter(new UploadCallTwo());
        rl_add_one.setOnClickListener(v -> getPermissionTwo());
        rl_add_two.setOnClickListener(v -> getPermissionTwo());
        rl_add_three.setOnClickListener(v -> getPermissionTwo());
    }

    @OnClick(R.id.bt_save)
    public void save() {
        String realName = et_realname.getText().toString().trim();
        String address = et_address.getText().toString().trim();
        String number = et_number.getText().toString().trim();
        if (TextUtils.isEmpty(realName)) {
            UIUtils.showToastSafe("真实姓名不能为空");
            return;
        }
//        if (TextUtils.isEmpty(address)) {
//            UIUtils.showToastSafe("地址不能为空");
//            return;
//        }
        if (TextUtils.isEmpty(number)) {
            UIUtils.showToastSafe("证件号不能为空");
            return;
        }
//        if (TextUtils.isEmpty(sex)) {
//            UIUtils.showToastSafe("性别不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(birthday)) {
//            UIUtils.showToastSafe("生日不能为空");
//            return;
//        }
        if (TextUtils.isEmpty(imgPathone)) {
            UIUtils.showToastSafe("请上传身份证正面");
            return;
        }
        if (TextUtils.isEmpty(imgPathtwo)) {
            UIUtils.showToastSafe("请上传身份证反面");
            return;
        }
//        String filePath = imagePathOne;
//        if (!imagePathTwo.equals("")) {
//            filePath = imagePathOne + "," + imagePathTwo;
//        }
//        if (!imagePathThree.equals("")) {
//            filePath = imagePathOne + "," + imagePathTwo + "," + imagePathThree;
//        }
//        if (TextUtils.isEmpty(filePath)) {
//            UIUtils.showToastSafe("生活照不能为空");
//            return;
//        }
        identityCheckedPresenterTwo.reqeust("Bearer " + token, number, realName, imgPathone + "," + imgPathtwo, "");//缺少一个mid
    }

    private void getPermissionTwo() {
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbumTwo();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {

                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");

                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission();
                    }

                });
    }

    private void showAlbumTwo() {
        PictureSelector.create(IdentityCheckedActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(100);

    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

//    @OnClick(R.id.rl_sex)
//    public void chooseSex() {
//        chooseSexDialog();
//    }
//
//    @OnClick(R.id.rl_birthday)
//    public void chooseBirthday() {
//        chooseBirthdayDialog();
//    }

    @OnClick({R.id.iv_address, R.id.et_address})
    public void chooseAddress() {
        showChooseArea();
    }

    private void showChooseArea() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideCounty(true);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                et_address.setText(province.getAreaName() + city.getAreaName());
            }
        });
        task.execute("四川", "成都");
    }

    class EditUserInfoCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("提交成功，请等待审核");
//            intent(FaceCheckActivity.class);
            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {
            if (TextUtils.isEmpty(e.getDisplayMessage())) {
                UIUtils.showToastSafe("认证失败，请检查您的信息");
            } else {
                UIUtils.showToastSafe(e.getDisplayMessage());
            }
        }
    }

    @OnClick(R.id.rl_add_img_one)
    public void addImgOne() {
        type = 0;
        getPermission();
    }

    @OnClick(R.id.rl_add_img_two)
    public void addImgTwo() {
        type = 1;
        getPermission();
    }

    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private void getPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbum();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {

                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");

                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission();
                    }

                });
    }

    private void showAlbum() {
        PictureSelector.create(IdentityCheckedActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                if (type == 0) {
                    ll_add_img_one.setVisibility(View.GONE);
                    iv_face_one.setVisibility(View.GONE);
                    ll_progress.setVisibility(View.VISIBLE);
                    GlideUtils.loadImgTwo(IdentityCheckedActivity.this, localMedia.get(0).getCompressPath(), 30, iv_face_one);
                } else {
                    ll_add_img_two.setVisibility(View.GONE);
                    iv_face_two.setVisibility(View.GONE);
                    ll_progress_two.setVisibility(View.VISIBLE);
                    GlideUtils.loadImgTwo(IdentityCheckedActivity.this, localMedia.get(0).getCompressPath(), 30, iv_face_two);
                }
                uploadImagePresenter.reqeust(localMedia.get(0).getCompressPath(), "Bearer " + token);
            }
        } else if (requestCode == 100) {
            if (data != null) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                uploadImage(localMedia.get(0).getCompressPath());
            }
        }
    }

    private void uploadImage(String imagePath) {
        if (imagePathOne.equals("")) {
            rl_add_one.setVisibility(View.GONE);
            rl_add_two.setVisibility(View.VISIBLE);
//            iv_img_one.setImageBitmap(BitmapFactory.decodeFile(imagePath));
//            Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
            iv_img_one.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        } else {
            if (imagePathTwo.equals("")) {
                rl_add_two.setVisibility(View.GONE);
                rl_add_three.setVisibility(View.VISIBLE);
                iv_img_two.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            } else {
                rl_add_three.setVisibility(View.GONE);
                iv_img_three.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            }
        }
        uploadImagePresenterTwo.reqeust(imagePath, "Bearer " + token);
    }

    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
//            UIUtils.showToastSafe("图片上传成功");
            if (type == 0) {
                imgPathone = data;
                ll_add_img_one.setVisibility(View.GONE);
                iv_face_one.setVisibility(View.VISIBLE);
                ll_progress.setVisibility(View.GONE);
//                GlideUtils.loadImgTwo(FaceCheckActivity.this, Constant.BASE_URL + data, 30, iv_face_one);
            } else {
                imgPathtwo = data;
                ll_add_img_two.setVisibility(View.GONE);
                iv_face_two.setVisibility(View.VISIBLE);
                ll_progress_two.setVisibility(View.GONE);
//                GlideUtils.loadImgTwo(FaceCheckActivity.this, Constant.BASE_URL + data, 30, iv_face_two);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入含有不合法的内容或图片，请遵守用户协议相关内容");
        }
    }

    class UploadCallTwo implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            if (imagePathOne.equals("")) {
                imagePathOne = data;
            } else {
                if (imagePathTwo.equals("")) {
                    imagePathTwo = data;
                } else {
                    imagePathThree = data;
                }
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入含有不合法的内容或图片，请遵守用户协议相关内容");
        }
    }


    @Override
    protected void destoryData() {

    }
}
